package org.example.aop;

import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.example.util.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wxm
 * @date 2025/2/25 9:26
 */
@Aspect
@Component
public class HttpRequestAspect {
    private static final Logger logger = LoggerFactory.getLogger(HttpRequestAspect.class);

    // 定义切入点，匹配org.example.service.impl包下的所有方法
    @Pointcut("execution(* org.example.service.impl.DemoServiceImpl.testAop(..))")
    public void testAop() {
    }

    // 前置通知，在目标方法执行之前执行
    @Before("testAop()")
    public void beforeServiceMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        logger.info("Before executing method: {}", methodName);
        try {
            // 获取 HttpUtils 单例实例
            HttpUtils httpUtils = HttpUtils.getInstance();

            // 定义请求 URL
            String url = "http://127.0.0.1:8080/api/testGetUrl?fileName=test.txt";
            // 定义请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");

            // 发送 GET 请求
            String getResponse = httpUtils.sendGetRequest(url, headers);
            System.out.println("GET Response: " + getResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 后置通知，在目标方法执行之后执行
    @After("testAop()")
    public void afterServiceMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        logger.info("After executing method: {}", methodName);

        try {
            // 获取 HttpUtils 单例实例
            HttpUtils httpUtils = HttpUtils.getInstance();

            // 定义请求 URL
            String url = "http://127.0.0.1:8080/api/testPostUrl";
            // 定义请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            // JSONObject body = new JSONObject();
            // body.put("fileName", "test.txt");
            // 发送 POST 请求
            String postResponse = httpUtils.sendPostRequest(url, "fileName=1", headers);
            System.out.println("POST Response: " + postResponse);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
